import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-profession-add',
  templateUrl: './profession-add.component.html',
  styleUrls: ['./profession-add.component.css']
})
export class ProfessionAddComponent implements OnInit {

  validateForm: FormGroup;
  // 新增时为true
  isAdd = true;
  constructor(
    private activeRoute: ActivatedRoute,
    private fb: FormBuilder,
    private router: Router
  ) { }

  ngOnInit(): void {
    const snapshot = this.activeRoute.snapshot;
    if (snapshot && snapshot.queryParams && Object.keys(snapshot.queryParams).length) {
      this.isAdd = false;
      const { id, name } = snapshot.queryParams;
      snapshot.data = { breadcrumb: name };

      // 根据id查询出详情
      const proInfo = {
        id: 1,
        name: '战士',
        weapon: '剑',
        hero: '地狱咆哮',
        skill: '武器',
        status: 'A',
      };

      this.validateForm = this.fb.group({
        name: [proInfo.name, Validators.required],
        weapon: [proInfo.weapon, Validators.required],
        hero: [proInfo.hero, Validators.required],
        skill: [proInfo.skill, Validators.required],
        status: [proInfo.status, Validators.required],
      });


    } else {
      this.isAdd = true;
      snapshot.data = { breadcrumb: '新增种族' };
      this.validateForm = this.fb.group({
        name: [null, Validators.required],
        weapon: [null, Validators.required],
        hero: [null, Validators.required],
        skill: [null, Validators.required],
        status: [null, Validators.required],
      });
    }
  }


  cancelHandle(): void {
    this.router.navigate(['/profession']);
  }

  saveHandle(): void {
    for (const i in this.validateForm.controls) {
      if (this.validateForm.controls.hasOwnProperty(i)) {
        const value = this.validateForm.controls[i];
        value.markAsDirty();
        value.updateValueAndValidity();
      }
    }

    if (this.validateForm.status === 'INVALID') {
      return;
    }

    // 保存
    console.warn(this.validateForm.value);
  }

}
